import { Meeting } from '@/api/manager/meeting'
import { Mt } from '@/api/manager/mt'
import shallow from 'zustand/shallow'
import { isMatch } from './utils/utils'
import { orgTreeRx, useOrgTreeStore } from './blocks/main/organizeTree/store'
import { getCurrentTabType, paramsRx, useParamsStore } from './blocks/main/store'
import { useTableAllStore } from './blocks/main/table/all/store'
import { MccModel } from './blocks/main/table/all/translator'
import { getItemByMtKey, getItemInTree, meetingListSort, mtListSort } from './blocks/main/table/all/utils'
import { useTableLiveStore } from './blocks/main/table/live/store'
import { useVipStore } from './blocks/vip/store'
import { useTableOftenStore } from './blocks/main/table/often/store'
import { oftenMtSort } from './blocks/main/table/often/utils'
import { mtListInteractiveSort } from './blocks/main/table/interactive/utils'
import { useTableInteractiveStore } from './blocks/main/table/interactive/store'
import { useTableDcsStore } from './blocks/main/table/dcs/store'
import { useTableOrgStore } from './blocks/main/table/organize/store'
import { getItemInOrgTree, getOrgItemById } from './blocks/main/organizeTree/utils'
import { combineOrgTree, OrgCreateTreeTranslator, OrgFlatTreeTranslator } from './blocks/main/organizeTree/translator'
import { useActionButtonsStore } from './blocks/main/actionButtons/store'
import { actionButtonsUnCheckAll } from './store.actionButton'
import { orgItemCheck } from './store.orgTree'
import { getOperateOnline, operateSplitDropDown } from './components'
import { useMccStore } from './store'
import { interval, merge } from 'rxjs'
import { bufferTime, filter, map, mergeMap, startWith, switchMap, take } from 'rxjs/operators'
import { fromPromise } from './utils/operator'
import { OrgModel } from '@/api/manager/organize/interface'
import { transOrg } from '@/api/manager/organize/translator'
import { orgMtSort } from './blocks/main/table/organize/utils'
import { transOften } from '@/api/manager/often/translator'
import { useGlobalStore } from '@/store/global'
import { defaultPersonalConfig } from '@/api/personalConfig/interface'
import { mcc_sub_smcu_mt_del } from './store.comted'
import { fetchOftenList } from '@/api/manager/often'
import { fetchAllMccMts, fetchGetMccOrg } from '@/api/manager/main'
function setTableItemAction() {
	const user = useGlobalStore.getState().user
	const isSubMeeting = useTableAllStore.getState().tree.mcc.confLevel === 1
	const isDcs = useTableDcsStore.getState().isDcs
	const config = useMccStore.getState()
	const operate = getOperateOnline({
		config,
		isSubMeeting,
		isDcs,
		user: { enable_dcs: user?.enable_dcs || 0, enable_video: user?.enable_video || 0 },
	})
	const result = operateSplitDropDown(operate, user?.personal_config || defaultPersonalConfig)
	useParamsStore.setState({
		tableItemAction: result,
	})
}
export function makeMainSubscribe() {
	useParamsStore.subscribe(
		(state) => state.tab,
		(tab) => {
			const SWITCH = useGlobalStore.getState().SWITCH
			const prevTree = useOrgTreeStore.getState().tree
			const currentOrgId = useParamsStore.getState().currentOrgId
			const allTree = prevTree.filter((x) => x.id === 'all')
			const tree = combineOrgTree(allTree, tab, SWITCH)
			getItemInOrgTree(tree, (item) => (item.status.isChecked = item.id === currentOrgId))
			useOrgTreeStore.setState({
				tree: [...tree],
			})
		}
	)
	useTableAllStore.subscribe(
		(state) => state.tree,
		(tree) => {
			const prevTab = useParamsStore.getState().tab
			let currentMeeting = getItemByMtKey(tree, '0.0.0.0_0')
			let onlineSize = 0,
				size = 0
			if (currentMeeting) {
				size = currentMeeting.children.filter(
					(x) => x.mcc.isMt || (!x.mcc.isMt && !x.mcc.status.isOnline)
				).length
				onlineSize = currentMeeting.children.filter((x) => x.mcc.isMt && x.mcc.status.isOnline).length
			}
			prevTab.all.onlineSize = onlineSize
			prevTab.all.size = size
			useParamsStore.setState({
				tab: { ...prevTab },
			})
		}
	)
	useTableOftenStore.subscribe(
		(state) => state.list,
		(list) => {
			const prevTab = useParamsStore.getState().tab
			let onlineSize = list.filter((x) => x.mcc.status.isOnline).length,
				size = list.length
			prevTab.often.onlineSize = onlineSize
			prevTab.often.size = size
			useParamsStore.setState({
				tab: { ...prevTab },
			})
		}
	)
	useTableInteractiveStore.subscribe(
		(state) => state.list,
		(list) => {
			const prevTab = useParamsStore.getState().tab
			let onlineSize = list.filter((x) => x.mcc.status.isOnline).length,
				size = list.length
			prevTab.interactive.onlineSize = onlineSize
			prevTab.interactive.size = size
			useParamsStore.setState({
				tab: { ...prevTab },
			})
		}
	)
	useTableDcsStore.subscribe(
		(state) => state.list,
		(list) => {
			const prevTab = useParamsStore.getState().tab
			let onlineSize = list.filter((x) => x.mcc.status.isOnline).length,
				size = list.length
			prevTab.dcs.onlineSize = onlineSize
			prevTab.dcs.size = size
			useParamsStore.setState({
				tab: { ...prevTab },
			})
		}
	)
	useTableLiveStore.subscribe(
		(state) => ({
			list: state.list,
			isLive: state.isLive,
		}),
		(cur) => {
			const prevTab = useParamsStore.getState().tab
			prevTab.live.size = cur.list.length
			prevTab.live.guestSize = cur.list.filter((x) => x.live.isGuest).length
			prevTab.live.canShow = cur.isLive
			useParamsStore.setState({
				tab: { ...prevTab },
			})
		},
		{
			equalityFn: shallow,
		}
	)
	useTableLiveStore.subscribe(
		(state) => state.isLive,
		(isLive) => {
			if (getCurrentTabType() === 'live' && !isLive) {
				useParamsStore.setState({ currentTab: 'all' })
				const tree = useOrgTreeStore.getState().tree
				let m = tree.find((x) => x.id === 'all')
				if (m) orgItemCheck(m)
			}
		}
	)
	useTableDcsStore.subscribe(
		(state) => state.isDcs,
		(isDcs) => {
			//tab变动
			if (getCurrentTabType() === 'dcs' && !isDcs) {
				useParamsStore.setState({ currentTab: 'all' })
				const tree = useOrgTreeStore.getState().tree
				let m = tree.find((x) => x.id === 'all')
				if (m) orgItemCheck(m)
			}
			const prevTab = useParamsStore.getState().tab
			prevTab.dcs.canShow = isDcs
			useParamsStore.setState({
				tab: { ...prevTab },
			})
			//终端操作按钮
			setTableItemAction()
		},
		{
			fireImmediately: true,
		}
	)
	useTableAllStore.subscribe(
		(state) => state.tree.mcc.confLevel === 1,
		() => {
			//终端操作按钮
			setTableItemAction()
		},
		{
			fireImmediately: true,
		}
	)
	useMccStore.subscribe(
		(state) => ({
			meetingType: state.mccInfo.meetingType,
			encryptionType: state.mccInfo.encryptionType,
			isUpload: state.mccInfo.isUpload,
		}),
		() => {
			//终端操作按钮
			setTableItemAction()
		},
		{
			equalityFn: shallow,
			fireImmediately: true,
		}
	)
	useGlobalStore.subscribe(
		(state) => ({
			user: state.user,
			serverInfo: state.serverInfo,
		}),
		(cur) => {
			//终端操作按钮
			setTableItemAction()
		},
		{
			equalityFn: shallow,
		}
	)

	/**
	 * 此处会议信息接口返回较快 tableSort已设置 , user接口返回较慢覆盖了tableSort
	 * 但智能级联必须默认组织架构，
	 * */
	function setTableSort() {
		const smartCascadeMode = useMccStore.getState().mccInfo.smartCascadeMode
		const mt_order_type = useGlobalStore.getState().user?.personal_config?.mt_order_type
		if (smartCascadeMode === 1) {
			useParamsStore.setState({ tableSort: 3 })
		} else {
			useParamsStore.setState({ tableSort: mt_order_type })
		}
	}

	useGlobalStore.subscribe(
		(state) => state.user?.personal_config?.mt_order_type,
		(cur) => {
			if (cur) {
				setTableSort()
			}
		}
	)
	useMccStore.subscribe(
		(state) => state.mccInfo.smartCascadeMode,
		(cur) => {
			if (cur === 1) {
				setTableSort()
			}
		}
	)

	useVipStore.subscribe(
		(state) => state.list,
		(list) => {
			const s = list.map((x) => x.mtKey).join('$$')
			useParamsStore.setState({ vipSort: s })
		}
	)
	//搜索，tab 切换, vip列表 和 sort排序  变化带动互动终端或者全部终端,常用终端等列表变化
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			sortType: state.tableSort,
			currentTab: state.currentTab,
			vipSort: state.vipSort,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'all') {
				const vipMtKeyList = cur.vipSort.split('$$')
				const tree = useTableAllStore.getState().tree
				getItemInTree(tree, (item) => {
					if (item.children) {
						let mtList = item.children
							.filter((x) => x.mcc.isMt)
							.map((x) => {
								x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
								return x
							}) as MccModel<Mt>[]
						let meetingList = item.children
							.filter((x) => !x.mcc.isMt)
							.map((x) => {
								if (!x.mcc.status.isOnline) {
									x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
								}
								return x
							}) as MccModel<Meeting>[]
						const resultMtList = mtListSort(mtList, cur.sortType, vipMtKeyList)
						const resultMeetingList = meetingListSort(meetingList, cur.sortType)
						item.children = [...resultMtList, ...resultMeetingList]
						//如果是搜索变动，那么默认展开下级
						if (cur.keywords !== prev.keywords) {
							if (cur.keywords === '' && item.mcc.confLevel === 3) {
								item.status.isOpen = false
							} else {
								item.status.isOpen = true
							}
						}
					}
				})
				useTableAllStore.setState({
					tree: { ...tree },
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			currentOrgId: state.currentOrgId,
			currentTab: state.currentTab,
			vipSort: state.vipSort,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'often') {
				const vipMtKeyList = cur.vipSort.split('$$')
				const list = useTableOftenStore.getState().list
				let result = oftenMtSort(list, vipMtKeyList).map((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
					return x
				})
				useTableOftenStore.setState({
					list: result,
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			sortType: state.tableSort,
			currentOrgId: state.currentOrgId,
			currentTab: state.currentTab,
			vipSort: state.vipSort,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'interactive') {
				const vipMtKeyList = cur.vipSort.split('$$')
				const list = useTableInteractiveStore.getState().list
				let result = mtListInteractiveSort(list, cur.sortType, vipMtKeyList).map((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
					return x
				})
				useTableInteractiveStore.setState({
					list: result,
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			currentOrgId: state.currentOrgId,
			currentTab: state.currentTab,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'dcs') {
				const list = useTableDcsStore.getState().list
				list.forEach((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
				})
				useTableDcsStore.setState({
					list: [...list],
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			currentTab: state.currentTab,
			currentOrgId: state.currentOrgId,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'live') {
				const list = useTableLiveStore.getState().list
				list.forEach((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
				})
				useTableLiveStore.setState({
					list: [...list],
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	useParamsStore.subscribe(
		(state) => ({
			keywords: state.keywords,
			currentOrgId: state.currentOrgId,
		}),
		(cur, prev) => {
			if (getCurrentTabType() === 'org') {
				let list = useTableOrgStore.getState().list
				const organizeTree = useOrgTreeStore.getState().tree
				let orgItem = getOrgItemById(organizeTree, cur.currentOrgId)
				if (orgItem) {
					let mtKeys = [] as string[]
					getItemInOrgTree([orgItem], (item) => {
						mtKeys = [...mtKeys, ...item.org.users.map((x) => x.mtKey)]
					})
					list.forEach((x) => {
						if (mtKeys.includes(x.mtKey)) {
							x.status.isMatchOrgTree = true
						} else {
							x.status.isMatchOrgTree = false
						}
						return x
					})
				}
				list.forEach((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, cur.keywords)
				})
				useTableOrgStore.setState({
					list: [...list],
				})
			}
		},
		{
			equalityFn: shallow,
		}
	)
	//底部按钮
	useParamsStore.subscribe(
		(state) => ({
			actionButtonList: state.actionButtonList,
			currentTab: state.currentTab,
			tableSort: state.tableSort,
			currentOrgId: state.currentOrgId,
		}),
		(cur, prev) => {
			let list = cur.actionButtonList
			if (getCurrentTabType() === 'live') {
				list = []
			}
			actionButtonsUnCheckAll()
			useActionButtonsStore.setState({
				screenList: [...list],
			})
		},
		{
			equalityFn: shallow,
		}
	)
	//组织架构树的刷新删除操作，采用rxjs;
	// mcc_mt等增加删除得重新刷新树，在离线刷新树 ，0/0 的数据直接删除
	useParamsStore.subscribe(
		(state) => state.tableSort,
		(cur) => {
			paramsRx.tableSort$.next()
		},
		{
			fireImmediately: true,
		}
	)
}
export const makeRxSubscribe = () => {
	/** 组织架构树 */
	orgTreeRx.reload$
		.pipe(
			filter(() => {
				const isSuperMeeting = useMccStore.getState().mccInfo.superMtNum
				return !isSuperMeeting
			}),
			//级联节点等操作更新需要重新获取常用终端，保证列表值的正确性
			switchMap(() => {
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				return fromPromise(fetchOftenList(meetingMoid))
			}),
			map((mts) => {
				const keywords = useParamsStore.getState().keywords
				const vipList = useVipStore.getState().list
				let list = mts
					? mts
							.map((x) => transOften(x))
							.map((x) => {
								x.status.isMatchSearch = isMatch(x.mcc, keywords)
								return x
							})
					: []
				const vipMtKeyList = vipList.map((x) => x.mtKey)
				let result = oftenMtSort(list, vipMtKeyList)
				return result
			})
		)
		.subscribe((v) => {
			useTableOftenStore.setState({
				list: v,
			})
		})
	merge(paramsRx.tableSort$, orgTreeRx.addMt$, orgTreeRx.reload$)
		.pipe(
			filter(() => {
				const sortType = useParamsStore.getState().tableSort
				return sortType === 3
			}),
			bufferTime(500),
			filter((arr) => arr.length > 0),
			switchMap(() => {
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				return fromPromise(fetchGetMccOrg(meetingMoid))
			}),
			map((res) => {
				const organizeTree = useOrgTreeStore.getState().tree
				const orgList = useTableOrgStore.getState().list
				const currentOrgId = useParamsStore.getState().currentOrgId
				const tab = useParamsStore.getState().tab
				const SWITCH = useGlobalStore.getState().SWITCH
				const flatOrg = OrgFlatTreeTranslator(res)
				const allTree = OrgCreateTreeTranslator(flatOrg)
				const tree = combineOrgTree(allTree, tab, SWITCH)
				let allItem = getOrgItemById(tree, currentOrgId)
				let mtKeys = [] as string[]
				if (allItem) {
					getItemInOrgTree([allItem], (item) => {
						mtKeys = [...mtKeys, ...item.org.users.map((x) => x.mtKey)]
					})
				}
				getItemInOrgTree(tree, (item) => {
					if (item.id === currentOrgId) {
						item.status.isChecked = true
					} else {
						item.status.isChecked = false
					}
					//保持旧树的展开关闭状态
					let orgItem = getOrgItemById(organizeTree, item.id)
					item.status.isOpen = orgItem ? orgItem.status.isOpen : item.status.isOpen
				})

				orgList.forEach((x) => {
					if (mtKeys.includes(x.mtKey)) {
						x.status.isMatchOrgTree = true
					} else {
						x.status.isMatchOrgTree = false
					}
				})
				return { tree, orgList }
			})
		)
		.subscribe(({ tree, orgList }) => {
			useOrgTreeStore.setState({
				tree: [...tree],
			})
			useTableOrgStore.setState({
				list: [...orgList],
			})
		})
	merge(paramsRx.tableSort$, orgTreeRx.reload$)
		.pipe(
			filter(() => {
				const sortType = useParamsStore.getState().tableSort
				return sortType === 3
			}),
			switchMap(() => {
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				return fromPromise(fetchAllMccMts(meetingMoid))
			}),
			map((mts) => {
				const organizeTree = useOrgTreeStore.getState().tree
				const keywords = useParamsStore.getState().keywords
				const currentOrgId = useParamsStore.getState().currentOrgId
				let list: OrgModel[] = []
				list = mts
					? mts
							.map((x) => transOrg(x))
							.map((x) => {
								x.status.isMatchSearch = isMatch(x.mcc, keywords)
								return x
							})
					: []
				let orgItem = getOrgItemById(organizeTree, currentOrgId)
				if (
					orgItem &&
					orgItem.id !== 'often' &&
					orgItem.id !== 'interactive' &&
					orgItem.id !== 'dcs' &&
					orgItem.id !== 'live'
				) {
					let mtKeys = [] as string[]
					getItemInOrgTree([orgItem], (item) => {
						mtKeys = [...mtKeys, ...item.org.users.map((x) => x.mtKey)]
					})
					list.forEach((x) => {
						if (mtKeys.includes(x.mtKey)) {
							x.status.isMatchOrgTree = true
						} else {
							x.status.isMatchOrgTree = false
						}
					})
				}
				list = orgMtSort(list)
				return list
			})
		)
		.subscribe((v) => {
			useTableOrgStore.setState({
				list: v,
			})
		})
	/** 呼叫 */
	paramsRx.tableItemCalling$
		.pipe(
			map((x) => [x, getCurrentTabType()] as const),
			mergeMap(([mtKey, curTabType]) =>
				interval(2000).pipe(
					map(() => false),
					take(1),
					startWith(true),
					map((isCalling) => ({ isCalling, mtKey, curTabType }))
				)
			)
		)
		.subscribe(({ isCalling, mtKey, curTabType }) => {
			if (curTabType === 'all') {
				const tree = useTableAllStore.getState().tree
				let item = getItemByMtKey(tree, mtKey)
				if (item) {
					item.status.isCalling = isCalling
					useTableAllStore.setState({
						tree: { ...tree },
					})
				}
			} else if (curTabType === 'often') {
				const list = useTableOftenStore.getState().list
				let item = list.find((x) => x.mtKey === mtKey)
				if (item) {
					item.status.isCalling = isCalling
					useTableOftenStore.setState({
						list: [...list],
					})
				}
			} else if (curTabType === 'interactive') {
				const list = useTableInteractiveStore.getState().list
				let item = list.find((x) => x.mtKey === mtKey)
				if (item) {
					item.status.isCalling = isCalling
					useTableInteractiveStore.setState({
						list: [...list],
					})
				}
			} else if (curTabType === 'org') {
				const list = useTableOrgStore.getState().list
				let item = list.find((x) => x.mtKey === mtKey)
				if (item) {
					item.status.isCalling = isCalling
					useTableOrgStore.setState({
						list: [...list],
					})
					if (!isCalling) {
						if (!item.mcc.mtid) {
							/**下级终端离线，直接删除 */
							/**必须加setTimeout，因为此时tableOrg还没更新，先删会导致数据会重置*/
							setTimeout(() => {
								mcc_sub_smcu_mt_del([item!.mtKey])
							})
						}
					}
				}
			}
		})
	paramsRx.tableCalling$
		.pipe(
			map(() => getCurrentTabType()),
			mergeMap((curTabType) =>
				interval(2000).pipe(
					map(() => false),
					take(1),
					startWith(true),
					map((isCalling) => ({ isCalling, curTabType }))
				)
			)
		)
		.subscribe(({ isCalling, curTabType }) => {
			if (curTabType === 'all') {
				const tree = useTableAllStore.getState().tree
				getItemInTree(tree, (item) => {
					if (!item.mcc.status.isOnline) {
						item.status.isCalling = isCalling
					}
				})
				useTableAllStore.setState({
					tree: { ...tree },
				})
			} else if (curTabType === 'often') {
				const list = useTableOftenStore.getState().list
				for (const item of list) {
					if (!item.mcc.status.isOnline) {
						item.status.isCalling = isCalling
					}
				}
				useTableOftenStore.setState({
					list: [...list],
				})
			} else if (curTabType === 'interactive') {
				const list = useTableInteractiveStore.getState().list
				for (const item of list) {
					if (!item.mcc.status.isOnline) {
						item.status.isCalling = isCalling
					}
				}
				useTableInteractiveStore.setState({
					list: [...list],
				})
			} else if (curTabType === 'org') {
				const list = useTableOrgStore.getState().list
				for (const item of list) {
					if (!item.mcc.status.isOnline) {
						item.status.isCalling = isCalling
					}
				}
				useTableOrgStore.setState({
					list: [...list],
				})
			}
		})
}
